package com.kll.tv.views

import android.content.Intent
import android.content.pm.PackageManager
import android.os.Build
import android.view.View
import androidx.core.app.ActivityCompat
import com.kll.carolinehmibiz.OperationManager
import com.kll.carolinehmibiz.model.AccountModel
import com.kll.carolinehmibiz.model.OperateListener
import com.kll.carolinehmibiz.net.bean.RefreshTokenResponse
import com.kll.carolinehmibiz.presentation.listener.ActiveProtocol
import com.kll.carolinehmibiz.presentation.presenter.ActivePresenter
import com.kll.tv.base.views.BaseActivity
import com.kll.tv.databinding.ActivityActiveBinding
import com.kll.tv.utils.AppToast
import com.tencent.qcloud.tuicore.util.SoftKeyBoardUtil


/**
 ** 激活页
 */
class ActiveActivity : BaseActivity<ActivePresenter>(), ActiveProtocol.IView {
    private lateinit var binding: ActivityActiveBinding
    private var phoneNumber: String = ""
    private var verifyCode: String? = ""
    private val PERMISSIONS_STORAGE = arrayOf(
        "android.permission.READ_PHONE_STATE"
    )
    private var permissionsState = 0

    override fun createPresenter(): ActivePresenter {
        return ActivePresenter(this, this)
    }

    override fun initViewBinding(): View {
        binding = ActivityActiveBinding.inflate(layoutInflater)
        return binding.root
    }

    override fun init() {
        // 获取权限
        permissionsState = getPermissions()

        initListener()
    }

    private fun initListener() {
        binding.tvGetCheckingCode.setOnClickListener {
            phoneNumber = binding.edtPhoneNumber.text.toString().trim()
            mPresenter.getVerifyCode(phoneNumber)
            binding.edtVerifyCode.isFocusable = true // 验证码输入框获取焦点
            binding.edtVerifyCode.isFocusableInTouchMode = true
            binding.edtVerifyCode.requestFocus()
        }
        binding.tvSubmit.setOnClickListener {
            if (permissionsState == 1) {
                phoneNumber = binding.edtPhoneNumber.text.toString().trim()
                verifyCode = binding.edtVerifyCode.text.toString().trim()
                mPresenter.activeDevice(phoneNumber, verifyCode!!)
            } else {
                permissionsState = getPermissions()
            }
        }

        binding.edtPhoneNumber.setOnFocusChangeListener(object : View.OnFocusChangeListener {
            override fun onFocusChange(v: View?, hasFocus: Boolean) {
                if (!hasFocus) {
                    SoftKeyBoardUtil.hideKeyBoard(binding.edtPhoneNumber.windowToken)
                } else {
                    SoftKeyBoardUtil.showSoftInput(binding.edtPhoneNumber)
                }
            }

        })
        binding.edtVerifyCode.setOnFocusChangeListener(object : View.OnFocusChangeListener {
            override fun onFocusChange(v: View?, hasFocus: Boolean) {
                if (!hasFocus) {
                    SoftKeyBoardUtil.hideKeyBoard(binding.edtVerifyCode.windowToken)
                } else {
                    SoftKeyBoardUtil.showSoftInput(binding.edtVerifyCode)
                }
            }

        })
    }

    private fun getPermissions(): Int {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {

            // 检测是否有手机状态的权限
            val permission = ActivityCompat.checkSelfPermission(
                this,
                PERMISSIONS_STORAGE[0]
            )
            if (permission != PackageManager.PERMISSION_GRANTED) {
                // 没有权限，去申请权限，会弹出对话框
                ActivityCompat.requestPermissions(
                    this,
                    PERMISSIONS_STORAGE,
                    321
                )
                return 0
            } else {
                return 1
            }
        } else {
            return 1
        }
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == 321) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                if (grantResults[0] != PackageManager.PERMISSION_GRANTED) {
                    // 如果没有获取权限，那么可以提示用户去设置界面--->应用权限开启权限
                    AppToast.show("拒绝获取权限不可激活！", 2000)
                    permissionsState = 0
                } else {
                    // 获取权限成功提示，可以不要
                    AppToast.show("获取权限成功！", 2000)
                    permissionsState = 1
                }
            }
        }
    }

    override fun showLoading() {

    }

    override fun stopLoading() {

    }

    override fun getVerifyCodeSuccessed() {
        AppToast.show("获取验证码成功！", 2000)
    }

    override fun getVerifyCodeFailed(code: Int, message: String) {
        AppToast.show(message, 2000)
        if (code == 102) {
            // token过期 刷新token
            OperationManager.getInstancce().refreshToken(object : OperateListener {
                override fun onSuccess(state: Int, obj: Any?) {
                    var data = obj as RefreshTokenResponse
                    AccountModel.getInstance(baseContext).updateUserToken(data.token)
                    mPresenter.getVerifyCode(phoneNumber)
                }

                override fun onFail(code: Int, message: String) {
                    AppToast.show(message, 2000)
                    if (code == 101) {
                        loginAgain()
                    }
                }

            })
        }
        if (code == 101) {
            loginAgain()
        }
    }

    override fun activeDeviceSuccessed() {
        AppToast.show("激活设备成功！", 2000)
        startActivity(Intent(this, MainActivity::class.java))
        finish()
    }

    override fun activeDeviceFailed(code: Int, message: String) {
        AppToast.show(message, 2000)
        if (code == 102) {
            // token过期 刷新token
            OperationManager.getInstancce().refreshToken(object : OperateListener {
                override fun onSuccess(state: Int, obj: Any?) {
                    var data = obj as RefreshTokenResponse
                    AccountModel.getInstance(baseContext).updateUserToken(data.token)
                    mPresenter.activeDevice(phoneNumber, verifyCode!!)
                }

                override fun onFail(code: Int, message: String) {
                    AppToast.show(message, 2000)
                    if (code == 101) {
                        loginAgain()
                    }
                }

            })
        }
        if (code == 101) {
            loginAgain()
        }
    }

    /**
     * 更改验证码倒计时ui回调
     */
    override fun loadAreaCodeTime(count: String, isBusying: Boolean) {
        if (isBusying) {
            binding.tvGetCheckingCode.text = count + "秒后发送"
        } else {
            binding.tvGetCheckingCode.text = count
        }
    }
}